/*
 * Projet industriel VAMP 2012 
 */
package com.vampmobile.android.activity;


import com.vampmobile.R;
import com.vampmobile.android.VampApplication;
import com.vampmobile.android.VampCommon.Commons.KINDS;
import com.vampmobile.android.db.VampDatabase;
import com.vampmobile.android.db.VampDatabase.VampDBHelper;
import com.vampmobile.android.tools.ActivityParameters;
import com.vampmobile.android.tools.ApplicationMenu;
import com.vampmobile.android.tools.ImageLoader;
import com.vampmobile.android.tools.ImageLoader.ImageCallback;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ResourceCursorAdapter;
import android.widget.TextView;
import android.widget.AbsListView.OnScrollListener;
/**
* class to display profile of user
 * FO && AM
 */
public class Theme extends Activity implements
GridView.OnScrollListener, GridView.OnItemClickListener {
	public static final String TAG = "THEMES";

	private GridView mGridView;
	private ItemAdapter mAdapter;
	public static VampDBHelper mDbHelper;
	private Cursor mCursor;
	private boolean mLoaded = false;
	private boolean mBusy = false;
	private ImageView mHomeTitle;
	private ImageView mHomeButton;
	private ImageView mBackButton;
	private ImageView mSearchButton;
	private ImageView mQuitButton;
	private ImageView mAccountButton;
	private ImageView mNavigation;
	/*
	 * method used by clicking on the list of item
	 */
	class ItemClickListener implements OnClickListener {

		private String name = null;
		private Long id = null;
		private KINDS kind = null;

		public ItemClickListener(KINDS kind) {
			super();
			this.kind = kind;
		}

		// case video and music
		public ItemClickListener(KINDS kind, Long id, String name) {
			super();
			this.kind = kind;
			this.id = id;
			this.name = name;
		}

		public void onClick(View mView) {
			switch (kind) {
			case THEMES:
				goPOI(id, name);
				break;
			case TOOLBAR:
				FrameLayout toolbar = (FrameLayout) findViewById(R.id.toolbar); 
				if (toolbar.getVisibility()!=View.VISIBLE)
					toolbar.setVisibility(View.VISIBLE);
				else
					toolbar.setVisibility(View.GONE);
				break;
			case QUIT:
				android.os.Process.killProcess(android.os.Process.myPid());
				java.lang.System.exit(0);
				finish();
				break;
			case SEARCH:
				break;
			case BACK:
				goHome();
				finish();
				break;
			case PROFILE_TITLE:
				Intent myIntent = new Intent();
				myIntent.setClass(getApplicationContext(), Profile.class);
				myIntent.setAction(Intent.ACTION_VIEW);
				finish();
				startActivity(myIntent);
				break;
			case HOME_TITLE:
				Intent i = new Intent();
				i.setClass(getApplicationContext(), Home.class);
				i.setAction(Intent.ACTION_VIEW);
				finish();
				startActivity(i);
				break;
			}

		}
	}


	/**
	 * Called when the activity is first created. Responsible for initializing
	 * the UI.
	 */
	@Override
	public void onCreate(Bundle icicle) {
		Log.i(TAG, "est OK");
		super.onCreate(icicle);
		setTitle(TAG);
		updatelistView();

	}
	
	private void updatelistView() {
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.theme_grid);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title);
		((TextView)findViewById(R.id.activityTitle)).setText(TAG);

		// button of title bar
		mHomeTitle = (ImageView) findViewById(R.id.home_title);
		mHomeTitle.setOnClickListener(new ItemClickListener(KINDS.TOOLBAR));
		// button of toolbar
		mHomeButton = (ImageView) findViewById(R.id.home);
		mHomeButton.setOnClickListener(new ItemClickListener(KINDS.HOME_TITLE));
		mBackButton = (ImageView) findViewById(R.id.back_button);
		mBackButton.setOnClickListener(new ItemClickListener(KINDS.BACK));
		mSearchButton = (ImageView) findViewById(R.id.search);
		mSearchButton.setOnClickListener(new ItemClickListener(KINDS.SEARCH));
		mQuitButton = (ImageView) findViewById(R.id.quit);
		mQuitButton.setOnClickListener(new ItemClickListener(KINDS.QUIT));
		mAccountButton = (ImageView) findViewById(R.id.account);
		mAccountButton.setOnClickListener(new ItemClickListener(KINDS.PROFILE_TITLE));		

		// Cursor for Adapter
		mDbHelper = VampDatabase.getInstance(getApplicationContext())
				.getDbHelper();		
		mCursor = mDbHelper.getThemes(null);

		// Adapter
		mAdapter = new ItemAdapter(Theme.this,
				 R.layout.home_themes_row, mCursor);
		mGridView = (GridView) findViewById(R.id.theme_grid);
		mGridView.setAdapter(mAdapter);

		mGridView.setOnScrollListener(this);
		mGridView.setOnItemClickListener(this);
		mGridView.setFastScrollEnabled(true);

		startManagingCursor(mCursor);	
	}

	@Override
	public void onResume() {
		super.onResume();
		onNewIntent(getIntent());
	}

	@Override
	public void finish() {
		if (mCursor != null) {
			mCursor.close();
			mCursor = null;
		}
		if (mDbHelper != null) {
			mDbHelper.close();
			mDbHelper = null;
		}
		super.finish();
	}

	@Override
	public void onPause() {
		super.onPause();
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
	}

	public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
		mCursor.moveToPosition(position);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		ApplicationMenu.onCreateOptionsMenu(this, menu);
		return true;
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		ApplicationMenu.onPrepareOptionsMenu(this, menu);
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		ApplicationMenu.onOptionsItemSelected(this, item);
		return true;
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
	}

	private class ItemAdapter extends ResourceCursorAdapter  {
		private final Bitmap mDefaultImage;
		private final ImageLoader mImageLoader;

		public ItemAdapter(Context context, int layout, Cursor cursor) {
			super(context, layout, cursor, true);

			mImageLoader = VampApplication.getInstance().getImageLoader();
			mDefaultImage = BitmapFactory.decodeResource(getResources(),
					R.drawable.home_theme);
		}

		@Override
		public View newView(Context context, Cursor cursor, ViewGroup parent) {
			final View view = super.newView(context, cursor, parent);
			final ViewCache cache = new ViewCache();
			cache.desc = (TextView) view
					.findViewById(R.id.theme_desc);
			cache.thumbnail = (ImageView) view
					.findViewById(R.id.theme_img);

			view.setTag(cache);

			return view;
		}

		@Override
		public void bindView(View view, Context context, Cursor cursor) {
			ViewCache cache = (ViewCache) view.getTag();
			cache.id = cursor.getLong(cursor
					.getColumnIndex(VampDatabase.BASE_ID_COL));
			cache.desc.setText(cursor.getString(cursor.getColumnIndex(VampDatabase.THEME_DESCRIPTION_COL)));


			
			view.setOnClickListener(new ItemClickListener(
					KINDS.THEMES, cache.id, cache.desc.getText().toString()));

			cache.thumbnail.setImageBitmap(mDefaultImage);
			// Image si existe
			cache.pendingThumbnailUrl = null;
			String imgURL = cursor.getString(cursor
					.getColumnIndex(VampDatabase.THEME_IMGURL_COL));
			cache.pendingThumbnailUrl = imgURL;
			cache.lazyPending = false;

			if (!TextUtils.isEmpty(cache.pendingThumbnailUrl)) {

				if (!mBusy
						|| mImageLoader
								.isImageLoaded(cache.pendingThumbnailUrl)) {
					setViewThumbnail(view, cache);
				} else {
					cache.thumbnail.setImageBitmap(mDefaultImage);
					cache.thumbnail.setTag(cache.pendingThumbnailUrl);

					cache.lazyPending = true;
				}
			} else {
				cache.thumbnail.setImageBitmap(mDefaultImage);
			}
		}
		
		public void setViewThumbnail(View view, final ViewCache cache) {
			cache.lazyPending = false;

			Bitmap cached = mImageLoader.loadImage(cache.pendingThumbnailUrl,
					new ImageCallback() {
						public void onSuccess(String url, Bitmap image) {
							if (cache.pendingThumbnailUrl == url) {
								cache.thumbnail.setTag(null);
								cache.thumbnail.setImageBitmap(image);
							}
						}

						public void onFailure(String url) {
							Log.w(TAG, "Loading Failed: " + url);
						}
					});

			if (cached == null) {
				cached = mDefaultImage;
			}
			cache.thumbnail.setImageBitmap(cached);
		}


		public void lazyBindViews() {
			GridView view = mGridView;
			int first = view.getFirstVisiblePosition();
			int count = view.getChildCount();

			for (int i = 0; i < count; i++) {
				View child = view.getChildAt(i);
				ViewCache cache = (ViewCache) child.getTag();

				if (cache != null && cache.lazyPending) {
					setViewThumbnail(view, cache);
				}
			}
		}

		private class ViewCache {
			public boolean lazyPending = true;
			public String pendingThumbnailUrl;
			public ImageView thumbnail;
			public TextView desc;
			public Long id;
		}

	}

	public void goPOI(Long themeId, String name) {
		ActivityParameters.themetId = themeId;
		ActivityParameters.themeName = name;
		Intent myIntent = new Intent();
		myIntent.setClass(getApplicationContext(), Poi.class);
		myIntent.setAction(Intent.ACTION_VIEW);
		finish();
		startActivity(myIntent);		
	}
	
	public void goProfile() {
		Intent myIntent = new Intent();
		myIntent.setClass(getApplicationContext(), Profile.class);
		myIntent.setAction(Intent.ACTION_VIEW);
		finish();
		startActivity(myIntent);		
	}
	
	public void goHome() {
		Intent i = new Intent();
		i.setClass(getApplicationContext(), Home.class);
		i.setAction(Intent.ACTION_VIEW);
		finish();
		startActivity(i);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			goHome();
			finish();
			return true;
		}
		return false;
	}

	public void onScroll(AbsListView arg0, int arg1, int arg2, int arg3) {
		// TODO Auto-generated method stub
		
	}

	public void onScrollStateChanged(AbsListView view, int scrollState) {
		switch (scrollState) {
		case OnScrollListener.SCROLL_STATE_IDLE:
			mBusy = false;
			mAdapter.lazyBindViews();
			break;
		case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
		case OnScrollListener.SCROLL_STATE_FLING:
			mBusy = true;
			break;
		}
		
	}
}
